package edu.biwu.Cookie02;

import edu.biwu.utils.CookieUtils;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@WebServlet("/lastVisited")
public class LastVisited extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //防止中文乱码
        response.setContentType("text/html;charset=UTF-8");

        Cookie cookie = CookieUtils.getCookie(request.getCookies(), "lastVisited");

        if (cookie==null){
            response.getWriter().write("欢迎第一次访问");
        }else{
            String dateStr = cookie.getValue();
            //输出的时候我们要进行解码
            String encodeDate = URLDecoder.decode(dateStr, "UTF-8");
            response.getWriter().write("您上次访问的时间："+encodeDate);
        }
        String format = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(LocalDateTime.now());
        //在将日期放入cookie前 有些字符cookie不支持 我们要进行编码
        String encode = URLEncoder.encode(format, "UTF-8");
        Cookie lastVisited = new Cookie("lastVisited", encode);

        lastVisited.setMaxAge(7*24*60*60);
        lastVisited.setPath(request.getContextPath());
        lastVisited.setPath("/day07");
        response.addCookie(lastVisited);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}
